<?php

namespace App\Admin\Models;

use App\Admin\Models\BaseModel;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\MessageBag;
use Ixudra\Curl\Facades\Curl;
use Encore\Admin\Facades\Admin;
use DB;

class storeGoodsIn extends BaseModel
{
    //指定主键
    protected $primaryKey = 'sgiId';

    public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
    {
        $perPage = Request::get('per_page', 20);
        $page = Request::get('page', 1);

        $sgiBatchCode = urlencode(Request::get('sgiBatchCode', ''));
        $sgName = urlencode(Request::get('sgName', ''));

        $start = ($page-1)*$perPage;

		///////获取数据//////////////////////////////////////////////////////////////////////////////////////
		$sId = Admin::user()->sId;

		$url = $this->host."/storeGoodsIn/getList?page={$page}&perPage={$perPage}&scKey={$sId}&sgiBatchCode={$sgiBatchCode}&sgName={$sgName}";
		$response = Curl::to($url)->get();
		$data = $this->handelApiData($response);

		////////获取数据/////////////////////////////////////////////////////////////////////////////////////

		$total = $data['count'];

        extract($data['data']);

        $tags = static::hydrate($data['data']);

        $paginator = new LengthAwarePaginator($tags, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }

    /**
     * Add a basic where clause to the query.
     *
     * @param  string|array|\Closure  $column
     * @param  mixed   $operator
     * @param  mixed   $value
     * @param  string  $boolean
     * @return $this
     */
    public function where($column, $operator = null, $value = null, $boolean = 'and'){
    	// http://localhost:96/admin/remark/remarkTag?rtcId=1
    	// $column rtcId
    	// $operator 1
    	// $value null
    	// $boolean and
    	return $this;
    }

	// 保存提交的form数据
	public function save(array $options = Array())
	{

	    $attributes = $this->getAttributes();
	    $userName = Admin::user()->name;
	    $now = date('Y-m-d H:i:s', time());

	    if (isset($attributes['sgiId'])){

	    	$sgiNum = $_POST['sgiChangeNum'];

	    	if($sgiNum + $attributes['sgiSurplus'] < 0){
	    		$error = new MessageBag([
					'title'   => '提交失败',
			        'message' => '减少数量不能小于批次剩余数量'
			    ]);

			    return back()->with(compact('error'))->withInput();
	    	}

	    	$sgiInfo = DB::table('store_goods_in')->where('sgiId', $attributes['sgiId'])->first();
	    	DB::table('store_goods_in')
	    		->where('sgiId', $attributes['sgiId'])
	    		->update([
	    			'sgiNum' => $sgiInfo->sgiNum + $sgiNum,
	    			'sgiBatchPrice' => $attributes['sgiBatchPrice'] + ($sgiNum * $attributes['sgiUnitPrice']),
	    			'sgiSurplus' => $sgiInfo->sgiSurplus + $sgiNum,
	    			'updateUser' => $userName
	    		]);

	    	DB::table('store_goods')->where('sgId', $sgiInfo->sgId)->increment('sgNum', $sgiNum);
	    	return;
	    }
		$ignore = ['createUser', 'createTime', 'updateUser', 'updateTime'];
		$newAttributes = array();
		foreach($attributes as $key => $value){
			if (!in_array($key, $ignore)){
				$newAttributes[$key] = $value;
			}
		}

		$newAttributes['createUser'] = $userName;
		$url = $this->host."/storeGoodsIn/add";

	    $sId = Admin::user()->sId;
	    $newAttributes['scKey'] = $sId;
	    $newAttributes['sId'] = $sId;
		$response = Curl::to($url)
					->withData($newAttributes)
					->post();


		$data = json_decode($response, true);
		if (!isset($data['code'])){
			$error = new MessageBag([
		        'title'   => '系统错误',
		        'message' => '',
		    ]);

		    return back()->with(compact('error'));
		}
		if ($data['code'] == 0){

		    $error = new MessageBag([
		        'title'   => '保存失败',
		        'message' => $data['msg'],
		    ]);

		    return back()->with(compact('error'));

		}else{
		    $success = new MessageBag([
		        'title'   => '保存成功',
		        'message' => $data['msg'],
		    ]);

		    return back()->with(compact('success'));
		}

		return $this;
	}

	 // 获取单项数据展示在form中
	public function findOrFail($id)
	{
		$sgiInfo = DB::table('store_goods_in')->where('sgiId', $id)->first();

	    return static::newFromBuilder($sgiInfo);
	}

	public function getStoreGoodsList(){

		$sId = Admin::user()->sId;
		$url = $this->host."/storeGoods/getList?scKey={$sId}&page=1&perPage=1000&notChild=1&sgIsStorage=1";
    	$response = Curl::to($url)->get();
    	$data = $this->handelApiData($response);
    	$selectArray = array();
    	foreach ($data['data'] as $pInfo){
    		$selectArray[$pInfo['sgId']] = $pInfo['sgName'];
    	}

    	return $selectArray;

	}

}
